package com.yupi.project.config;

import com.yupi.project.annotation.SecureInvokeConfigurer;
import com.yupi.project.factory.MyThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Description: 线程池配置
 * Author: <a href="https://github.com/zongzibinbin">abin</a>
 * Date: 2023-04-09
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer, SecureInvokeConfigurer {

    public static final String COMMON_API_EXECUTOR = "commonApiExecutor";

    @Override
    public Executor getAsyncExecutor() {
        return commonApiExecutor();
    }

    @Override
    public Executor getSecureInvokeExecutor() {
        return commonApiExecutor();
    }

    @Bean(COMMON_API_EXECUTOR)
    public ThreadPoolTaskExecutor commonApiExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(4);
        executor.setQueueCapacity(1000);
        executor.setThreadNamePrefix("common-api-executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//满了由提交任务的当前线程处理。
        executor.setThreadFactory(new MyThreadFactory(executor));
        return executor;
    }
}
